package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.common.JSONUtil;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.redis.key.SeckillRedisKey;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by wolfcode-lanxw
 */
@RestController
@RequestMapping("/api/seckill/goods")
public class SeckillGoodController {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 压力测试
     * 优化前:
     *      请求数: 100 * 50
     *      吞吐量/QPS/TPS: 990.3/s
     * 优化后:
     *      请求数: 100 * 50
     *      QPS: 2296.7/s
     * @return
     */
    @GetMapping
    public Result<List<SeckillGoodVo>> list() {
        return Result.success(seckillGoodService.queryByCache());
    }

    @GetMapping("/{id}")
    public Result<SeckillGoodVo> detail(@PathVariable("id") Long id) {
        SeckillGoodVo vo = seckillGoodService.findByCache(id);
        return Result.success(vo);
    }

    @RequestMapping("/initData")
    public Result<?> initData() {
        List<SeckillGoodVo> list = seckillGoodService.listAll();
        for (SeckillGoodVo vo : list) {
            // 库存预减数据预热
            redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_GOODS_HASH.join(), vo.getId() + "", JSONUtil.toJSONString(vo));
            redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.join(), vo.getId() + "", vo.getStockCount() + "");
        }
        return Result.success();
    }
}
